package start.gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import jaxb.messages.Folder;
import jaxb.messages.Resource;

import start.StrongBoxClient;
import start.gui.audio.Playback;
import virtualHD.VirtualHDException;

public class BoxPanel extends ImagePanel implements ActionListener{

	private static final String EXIT_CMD = "EXIT";
	private static final String UPLOAD_CMD = "UPLOAD";
	private static final String CHROLE_CMD = "CHROLE";
	private static final String CHFOLDER_CMD = "CHFOLDER";

	public BoxPanel(String imagePath,StrongBoxClient hd) {
		super(imagePath,hd);

		downIcon = createIcon("images/download.png");
		delIcon = createIcon("images/delete.png");
		upIcon = createIcon("images/upload.png");
		chIcon = createIcon("images/friends.png");
		folderIcon = createIcon("images/folder.png");
		
		jf = new JFileChooser();
		jf.setCurrentDirectory(new File("."));
		
		currentFolder = hd.getUserID();

		setLayout(new BorderLayout());
		add(makeFolderPanel(),BorderLayout.PAGE_START);
		add(makeStatusPanel(),BorderLayout.LINE_START);
		add(makeTablePanel(),BorderLayout.CENTER);
		
		
		exitButton = new JButton("EXIT");
		exitButton.setActionCommand(EXIT_CMD);
		exitButton.addActionListener(this);
		add(exitButton,BorderLayout.PAGE_END);	
		
		//we add a view of user folder
		
		Folder folder = new Folder();
		folder.setUserid(currentFolder); //TODO
		try {
			Resource resources[] = sbc.view(folder);
			addRes2Table(resources);
		} catch (VirtualHDException e) {
			this.showPopup("WARNING", e.getMessage(), JOptionPane.WARNING_MESSAGE);
		}
		
		(new Playback("sounds/lock.wav")).execute();
		
	}


	private JPanel makeStatusPanel(){
		JPanel panel = new JPanel();
		panel.setOpaque(false);
		panel.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		Font userFont = new Font(Font.DIALOG,Font.HANGING_BASELINE,20);

		c.gridx = 0;
		c.gridy = 0;
		c.insets = new Insets(5,5,5,0);
		JLabel userLabel = new JLabel(" LOGGED AS ");
		userLabel.setForeground(Color.RED);
		userLabel.setFont(userFont);
		panel.add(userLabel,c);

		JLabel userL = new JLabel(sbc.getUserID());
		userL.setForeground(Color.RED);
		userL.setFont(userFont);
		c.gridx = 0;
		c.gridy = 1;
		c.insets = new Insets(5,0,5,0);
		panel.add(userL,c);

		c.gridx = 0;
		c.gridy = 2;
		c.insets = new Insets(5,10,5,0);
		c.fill = GridBagConstraints.HORIZONTAL;
		
		JButton chroleB = new JButton("Change permits");
		chroleB.setIcon(chIcon);
		chroleB.setOpaque(true);
		chroleB.setActionCommand(CHROLE_CMD);
		chroleB.addActionListener(this);
		panel.add(chroleB,c);
		
		c.gridx = 0;
		c.gridy = 3;
		c.fill = GridBagConstraints.HORIZONTAL;
		
		JButton uploadButton = new JButton("  Upload a file  ");
		uploadButton.setIcon(upIcon);
		uploadButton.setSize(chroleB.getSize());
		uploadButton.setActionCommand(UPLOAD_CMD);
		uploadButton.addActionListener(this);
		uploadButton.setOpaque(true);

		panel.add(uploadButton,c);
		
		progressBar = new JProgressBar();
		progressBar.setString("NO TRANSFER");
		progressBar.setForeground(Color.RED);
		c.gridx = 0;
		c.gridy = 4;
		c.fill = GridBagConstraints.HORIZONTAL;
		panel.add(progressBar,c);

		return panel;
	}

	private JPanel makeFolderPanel(){
		Font folderFont = new Font(Font.DIALOG,Font.ROMAN_BASELINE,20);
		
		JPanel panel = new JPanel();
		panel.setOpaque(false);

		panel.setLayout(new FlowLayout());
		
		dirL = new JLabel("CURRENT FOLDER: "+currentFolder);
		dirL.setFont(folderFont);
		dirL.setForeground(Color.RED);
		panel.add(dirL,FlowLayout.LEFT);
		
		//TODO implement get folder function for hd
		String folders[] = {"pasquale","giuseppe","gianni"};
		folderList = new JComboBox(folders);
		folderList.setSelectedIndex(0);
		panel.add(folderList);
		
		JButton changeFolder = new JButton("Change current folder");
		changeFolder.setIcon(folderIcon);
		changeFolder.setActionCommand(CHFOLDER_CMD);
		changeFolder.addActionListener(this);
		panel.add(changeFolder);

		/*GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;

		panel.add(new JLabel("Current folder: "),c);
		c.gridx = 1;
		c.gridy = 0;
		panel.add(changeFolder,c);*/
		return panel;
	}

	private JPanel makeTablePanel(){
		JPanel panel = new JPanel();
		panel.setOpaque(false);

		model = new DefaultTableModel(); //model for this table
		table = new JTable(model);
		model.addColumn("Filename");
		model.addColumn("Lastmod");
		model.addColumn("Size(KB)");
		model.addColumn("Download");
		model.addColumn("Delete");

		Action dowloadA = new AbstractAction()
		{
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e)
			{
				(new Playback("sounds/button.wav")).execute();
				int modelRow = Integer.valueOf( e.getActionCommand() );
				String filename = (String)model.getValueAt(modelRow, 0); //get filename
				Folder folder = new Folder();
				folder.setUserid(currentFolder);
				Resource resource = new Resource();
				resource.setName(filename);
				try {
					progressBar.setIndeterminate(true);
					sbc.get(folder, resource);
					
					showPopup("INFO","Download completed!",JOptionPane.INFORMATION_MESSAGE);
				} catch (VirtualHDException e1) {
					showPopup("ERROR",e1.getMessage(),JOptionPane.ERROR_MESSAGE);
				} finally{
					progressBar.setIndeterminate(false);
				}
			}
		};

		Action deleteA = new AbstractAction()
		{
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e)
			{
				(new Playback("sounds/button.wav")).execute();
				
				int modelRow = Integer.valueOf( e.getActionCommand() );

				String filename = (String)model.getValueAt(modelRow, 0);	//gets the file name
				Folder folder = new Folder();
				folder.setUserid(currentFolder);
				Resource resource = new Resource();
				resource.setName(filename);

				try {
					sbc.del(folder, resource);
					showPopup("INFO","Resource deleted!",JOptionPane.INFORMATION_MESSAGE);
					model.removeRow(modelRow);
				} catch (VirtualHDException e1) {
					showPopup("ERROR",e1.getMessage(),JOptionPane.ERROR_MESSAGE);
				}
			}
		};

		ButtonColumn downColumn = new ButtonColumn(table,dowloadA,3);
		ButtonColumn delColumn = new ButtonColumn(table,deleteA,4);
		table.setCellEditor(downColumn);
		table.setCellEditor(delColumn);

		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setOpaque(false);
		panel.add(scrollPane);

		return panel;
	}


	private void addRes2Table(Resource[] resources){
		for(int i=0;i<model.getRowCount();i++) //cleaning of rows
			model.removeRow(i);

		for(int i=0;i<resources.length;i++){
			Object data[] = {resources[i].getName(),
					resources[i].getLastMod(),
					Float.toString((float)resources[i].getSize()/1024),
					downIcon,delIcon};
			model.addRow(data);

		}
	}
	
	/*
	private JPanel makeExitPanel(){
		JPanel panel = new JPanel();
		panel.setOpaque(false);
		exitButton = new JButton("EXIT");
		exitButton.setOpaque(true);
		panel.add(exitButton,BorderLayout.CENTER);
		return panel;
	}*/



	private JTable table;
	private JComboBox folderList;
	private DefaultTableModel model;
	private JButton exitButton;
	private String currentFolder;
	private JProgressBar progressBar;
	private JFileChooser jf;
	
	private JLabel dirL;

	private ImageIcon downIcon;
	private ImageIcon delIcon;
	private ImageIcon upIcon;
	private ImageIcon chIcon;
	private ImageIcon folderIcon;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void actionPerformed(ActionEvent evt) {
		if(evt.getActionCommand().equals(EXIT_CMD)){//exit
			try {
				sbc.closeHD();
				(new Playback("sounds/close.wav")).execute();
			} catch (VirtualHDException e) {
				showPopup("ERROR",e.getMessage(),JOptionPane.ERROR_MESSAGE);
			}
			JFrame frame = (JFrame)SwingUtilities.getRoot(this);
			frame.setContentPane(new LoginPanel("images/cassaforte.jpg",sbc));
			frame.validate();
		}else if(evt.getActionCommand().equals(UPLOAD_CMD)){
			(new Playback("sounds/button.wav")).execute();
			
			int choice = jf.showDialog(this,"File to send:");
			if(choice == JFileChooser.APPROVE_OPTION){
				File f = jf.getSelectedFile();
				Folder folder = new Folder();
				folder.setUserid(currentFolder);
				Resource resource = new Resource();
				resource.setName(f.getName());
				try {
					progressBar.setIndeterminate(true);
					sbc.put(folder, resource);
					showPopup("INFO","Upload completed!",JOptionPane.INFORMATION_MESSAGE);
				} catch (VirtualHDException e) {
					showPopup("ERROR", e.getMessage(), JOptionPane.ERROR_MESSAGE);
				}finally{
					progressBar.setIndeterminate(false);
				}
			}
		}else if(evt.getActionCommand().equals(CHFOLDER_CMD)){
			(new Playback("sounds/button.wav")).execute();
			String f = (String)folderList.getSelectedItem();
			Folder folder = new Folder();
			folder.setUserid(f);
			try {
				Resource[] resources = sbc.view(folder);
				showPopup("INFO", "Directory changed!", JOptionPane.INFORMATION_MESSAGE);
				currentFolder = f;
				dirL.setText(f);
				addRes2Table(resources);
			} catch (VirtualHDException e) {
				showPopup("ERROR", e.getMessage(), JOptionPane.ERROR_MESSAGE);
			}
		}else if(evt.getActionCommand().equals(CHROLE_CMD)){
			(new Playback("sounds/button.wav")).execute();
			(new RoleFrame(sbc)).setVisible(true);
		}

	}

}
